use async_std::task;
use futures::executor::block_on;
use std::time::Duration;
use async_std::sync::{Arc,Mutex};

// Arc线程安全的Rc计数器，允许多线程安全共享访问变量，当引用数为0时内存自动释放，可以理解为Arc让变量实现Sync
// 如果需要多线程写，则需要Arc结合Mutex，可以理解为Sync+Clone=Send

#[test]
fn test_arc_mutex(){

    let x = Arc::new(Mutex::new(1));

    let tx = x.clone();
    task::spawn(async move {
        let mut tx = (*tx).lock().await;
        {
            *tx += 1;
        }
        println!("thread_1 x = {}", *tx);
    });

    let tx = x.clone();
    task::spawn(async move{
        let mut tx = (*tx).lock().await;
        {
            *tx += 1;
        }
        println!("thread_2 x = {}", *tx);
    });

    block_on(task::spawn(async {
        task::sleep(Duration::from_secs(5)).await;
    }));

}
